// components/Blank/blank.js
var apiJs = require('../../utils/util.js');
var appData = getApp().globalData;
var dataParamList = [];

var formId = 0;
var fields = [];
var formParam = new Array();

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    pageData: {
      type: Object
    }
  },



  /**
   * 组件的初始数据
   */
  data: {
    NowTime: apiJs.formatDate(new Date()),
    SelectIndex: 0
  },

  /**
   * 组件初始化事件
   */
  attached: function() {
    var fields = this.properties.pageData.Item.Fields;
    var dateTimeArr = [];
    var selectArr = [];
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].DataType == 'datetime') {
        var dateArr = new Object();
        dateArr.dIndex = i;
        dateArr.NewNowTime = this.data.NowTime;
        dateTimeArr.push(dateArr);
      }
      if (fields[i].DataType == 'int') {
        var arr = new Object();
        arr.sIndex = i;
        arr.NewSelectIndex = this.data.SelectIndex;
        selectArr.push(arr);
      }
    }

    this.setData({
      DateTimeSelect: dateTimeArr,
      SelectOptions: selectArr
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 绑定下拉选择事件
     */
    bindPickerChange: function(e) {
      var selectArr = this.data.SelectOptions;
      var selectIndx = e.detail.value;
      var index = e.currentTarget.dataset.index;
      if (selectArr != undefined && selectArr != null) {
        for (var i = 0; i < selectArr.length; i++) {
          if (index == selectArr[i].sIndex) {
            selectArr[i].NewSelectIndex = selectIndx;
          }
        }
      }
      this.setData({
        SelectOptions: selectArr
      })
    },
    /**
     * 下拉选择时间事件
     */
    bindTimeChange: function(e) {
      var dateTimeArr = this.data.DateTimeSelect;
      var value = e.detail.value;
      var index = e.currentTarget.dataset.index;
      if (dateTimeArr != undefined && dateTimeArr != null) {
        for (var i = 0; i < dateTimeArr.length; i++) {
          if (index == dateTimeArr[i].dIndex) {
            dateTimeArr[i].NewNowTime = value;
          }
        }
      }
      this.setData({
        DateTimeSelect: dateTimeArr
      })
    },

    /**
     * 提交表单
     */
    FormSubmit: function(e) {
      var _this = this;
      var IsSubmit = false;
      var lenIndex = 0;
      dataParamList = [];
      formId = e.detail.target.dataset.formid;
      formParam = e.detail.value;
      fields = _this.properties.pageData.Item.Fields;

      let p = new Promise(function(resolve, reject) {
        if (fields != null && fields.length > 0) {
          for (var i = 0; i < fields.length; i++) {
            lenIndex = lenIndex + 1;
            if (fields[i].PrimaryName != 'PRI') {
              var param = new Object();
              var field = fields[i].FieldEName;
              var strName = fields[i].FieldCName;
              param.FileName = field;
              param.FileValue = formParam[field];

              if (fields[i].DataType == 'varchar') {
                if (fields[i].VarcharObj.Checks != null && fields[i].VarcharObj.Checks.length > 0) {
                  //验证是否为必填
                  if (fields[i].VarcharObj.Checks[0] == 1) {
                    if (param.FileValue == null || param.FileValue == '') {
                      var msg = '请输入';
                      wx.showModal({
                        title: '提示',
                        content: msg + fields[i].FieldCName,
                        showCancel: false
                      })
                      resolve(false);
                      return;
                    }

                    if (fields[i].VarcharObj.MaxLength != "" || fields[i].VarcharObj.MinLength != "") {
                      if (fields[i].VarcharObj.MaxLength != "") {
                        if (param.FileValue.length > parseInt(fields[i].VarcharObj.MaxLength)) {
                          wx.showModal({
                            title: '提示',
                            content: strName + "长度不能大于" + fields[i].VarcharObj.MaxLength,
                            showCancel: false
                          })
                          resolve(false);
                          return;
                        }
                      }

                      if (fields[i].VarcharObj.MinLength != "") {
                        if (param.FileValue.length < parseInt(fields[i].VarcharObj.MinLength)) {
                          wx.showModal({
                            title: '提示',
                            content: strName + "长度不能小于" + fields[i].VarcharObj.MinLength,
                            showCancel: false
                          })
                          resolve(false);
                          return;
                        }
                      }

                      if (fields[i].VarcharObj.MaxLength != "" && fields[i].VarcharObj.MinLength != "") {
                        if (param.FileValue.length > parseInt(fields[i].VarcharObj.MaxLength) && param.FileValue.length < parseInt(fields[i].VarcharObj.MinLength)) {
                          wx.showModal({
                            title: '提示',
                            content: strName + "长度不能大于" + fields[i].VarcharObj.MaxLength + "并且不能小于" + fields[i].VarcharObj.MinLength,
                            showCancel: false
                          })
                          resolve(false);
                          return;
                        }
                      }
                      else
                        IsSubmit = true;

                    } else {
                      IsSubmit = true;
                    }
                  } else {
                    IsSubmit = true;
                  }

                  //验证是否勾选不能和已有数据重复 
                  if (fields[i].VarcharObj.Checks.length == 2) {
                    if (fields[i].VarcharObj.Checks[1] == 2) {
                      lenIndex = lenIndex - 1;
                      wx.request({
                        url: appData.apiurl + "mobile/api/MiniForm/JudgeMiniFormData",
                        method: "get",
                        data: {
                          custId: appData.custID,
                          formId: formId,
                          paramObj: JSON.stringify(param)
                        },
                        header: {
                          "content-type": "application/json",
                          'X_ManuName': appData.manuName
                        },
                        success: function(res) {
                          if (res.data.code == 1200 && res.data.content != "通过验证") {
                            wx.showModal({
                              title: '提示',
                              content: "已有重复的" + fields[lenIndex - 1].FieldCName + "，请重新输入",
                              showCancel: false
                            })
                            resolve(false);
                            return;
                          } else
                            IsSubmit = true;
                          lenIndex = lenIndex + 1;
                          if (lenIndex == fields.length && IsSubmit) {
                            resolve(true);
                          }
                        },
                        fail: function(res) {
                          wx.showModal({
                            title: '提示',
                            content: "已有重复的" + fields[lenIndex - 1].FieldCName + "，请重新输入",
                            showCancel: false
                          })
                          lenIndex = lenIndex + 1;
                          resolve(false);
                          return;
                        }
                      })
                    }
                  }
                } else {
                  IsSubmit = true;
                }
              }
              else{
                IsSubmit = true;
              }
              dataParamList.push(param);
            }
          }
          if (lenIndex == fields.length && IsSubmit) {
            resolve(true);
          }
        }
      });


      Promise.all([p]).then(res => {
        console.log(res);
        if (res[0]) {
          _this.SoureSubMit(_this, appData.custID, dataParamList);
        }
      });
    },

    SoureSubMit: function(_this, custId, dataParamList) {
      wx.showLoading({
        title: '提交中...',
        mask: true
      });
      wx.request({
        url: appData.apiurl + "mobile/api/MiniForm/AddMiniFormData",
        method: "get",
        data: {
          custId: custId,
          formId: formId,
          dataParam: JSON.stringify(dataParamList)
        },
        header: {
          "content-type": "application/json",
          'X_ManuName': appData.manuName
        },
        success: function(res) {
          wx.hideLoading()
          if (res.data.code == 1200 && res.data.content == "添加成功") {
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 2000
            });
          } else {
            wx.showModal({
              title: '错误',
              content: '提交失败',
              showCancel: false
            })
          }
          _this.FormReset();
        },
        fail: function(res) {
          wx.hideLoading();
          wx.showModal({
            title: '错误',
            content: '提交失败',
            showCancel: false
          })
        }
      })
    },
    /**
     * 重置
     */
    FormReset: function() {
      console.log('form发生了reset事件')
    }
  }
})